import java.io.*;
import java.net.*;
import java.lang.*;
import java.lang.reflect.InvocationTargetException;

public class Server implements Runnable 
{

	public void run()
	{
		ServerSocket server = null;
		try{
			server = new ServerSocket(4567);
		}catch(IOException ex) {
			System.err.println(ex);
		}

		while(true) {
			Socket sock = null;
			DataInputStream din = null;
			int type = 0;

			try{
				sock = server.accept();
				din  = new DataInputStream(sock.getInputStream());
				type = din.readInt();

				if(type==1) {
					//
					loadClass(sock);
					//
					Agent agent = readAgent(sock);
					Thread t = new Thread(agent);
					t.start();
				}

			}catch(IOException ex) {
				System.err.println(ex);
			}
		}
	}

	public void loadClass(Socket sock)
	{
		DataInputStream din  = null;
		try{
			din = new DataInputStream(sock.getInputStream());
			AgentLoader loader = new AgentLoader(sock);
			loader.loadClass("Police");
		}catch(IOException e) { }
		}catch(ClassNotFoundException e) { }
	}
	


	public Agent readAgent(Socket connect)
	{
		Agent agent = null;

		try{
			ObjectInputStream in 
				= new ObjectInputStream(connect.getInputStream());
			agent  = (Agent)in.readObject();
		}catch(IOException ex) {
			System.err.println(ex);
		}catch(ClassNotFoundException ex) {
			System.err.println(ex);
		}

		return agent;
	}

	public static void main(String[] args)
   	{
		Server server = new Server();
		Thread t = new Thread(server);
		t.start();
	}

}
